import {
  _decorator,
  Component,
  EventKeyboard,
  find,
  game,
  Input,
  input,
  KeyCode,
  Node,
  UITransform,
} from "cc";
const { ccclass, property } = _decorator;

@ccclass("board")
export class board extends Component {
  isMoving = false;
  speed = 3;

  start() {
    input.on(Input.EventType.KEY_DOWN, this.onKeyDown, this);
    input.on(Input.EventType.KEY_UP, this.onKeyUp, this);
  }

  update(deltaTime: number) {
    this.move();
  }

  move() {
    const bgNode = find("Canvas/background/img");
    const bgWidth = bgNode.getComponent(UITransform).contentSize.width;
    const { x, y } = this.node.position;

    const boardWidth = this.node.getComponent(UITransform).contentSize.width;
    const rightWall = bgWidth / 2;
    const leftWall = -bgWidth / 2;
    const boardRight = boardWidth / 2;
    const boardLeft = -boardWidth / 2;

    const isOverRight = x + boardRight + this.speed > rightWall;
    const isOverLeft = x + boardLeft + this.speed < leftWall;

    if (this.isMoving) {
      if (this.speed > 0 && isOverRight) {
        this.node.setPosition(rightWall - boardRight, y);
        return;
      }

      if (this.speed < 0 && isOverLeft) {
        this.node.setPosition(leftWall - boardLeft, y);
        return;
      }

      this.node.setPosition(x + this.speed, y);
    }
  }

  onKeyDown(event: EventKeyboard) {
    switch (event.keyCode) {
      case KeyCode.ARROW_LEFT:
        this.isMoving = true;
        this.speed = -3;
        break;
      case KeyCode.ARROW_RIGHT:
        this.isMoving = true;
        this.speed = 3;
        break;
      case KeyCode.SPACE:
        game.emit("launch-ball");
        break;
    }
  }

  onKeyUp(event: EventKeyboard) {
    switch (event.keyCode) {
      case KeyCode.ARROW_LEFT:
        this.isMoving = false;
        break;
      case KeyCode.ARROW_RIGHT:
        this.isMoving = false;
        break;
    }
  }
}
